import flask
import os
import json
from api.interface import UserOpe, ArticleOpe, CourseOpe, CommentOpe, ScoreOpe, VoteOpe

class Interface():
    def __init__(self):
        self.user = UserOpe()
        self.article = ArticleOpe()
        self.course = CourseOpe()
        self.comment = CommentOpe()
        self.score = ScoreOpe()
        self.vote = VoteOpe()

interface = Interface()

SAVING_PATH = os.path.join(os.path.dirname(__file__), 'static')

def add_routes(app):
    @app.route('/' )
    @app.route('/<path:path>')
    def hello_world(path=None):
        return flask.render_template('index.html')

# ================= user route =================
    @app.route('/api/getUser', methods=['POST'])
    def get_user() -> str:
        username = flask.request.json.get('username')
        return interface.user.get_user(username)

    @app.route('/api/userLogin', methods=['POST'])
    def user_login() -> bool:
        username = flask.request.json.get('username')
        password = flask.request.json.get('password')
        return json.dumps(interface.user.user_login(username, password))

    @app.route('/api/userRegister', methods=['POST'])
    def user_register() -> bool:
        username = flask.request.json.get('username')
        password = flask.request.json.get('password')
        secure_question = flask.request.json.get('secure_question')
        secure_answer = flask.request.json.get('secure_answer')
        isAdmin = flask.request.json.get('is_admin')
        return json.dumps(interface.user.user_register(username, password, secure_question, secure_answer, isAdmin))

    @app.route('/api/getSecureQuestion', methods=['POST'])
    def get_secure_question() -> str:
        username = flask.request.json.get('username')
        return interface.user.get_secure_question(username)

    @app.route('/api/checkSecureAnswer', methods=['POST'])
    def check_secure_answer() -> bool:
        username = flask.request.json.get('username')
        secure_answer = flask.request.json.get('secure_answer')
        return interface.user.check_secure_answer(username, secure_answer)

    @app.route('/api/deleteUser', methods=['POST'])
    def delete_user() -> None:
        username = flask.request.json.get('username')
        interface.user.delete_user(username)

    @app.route('/api/updateUser', methods=['POST'])
    def update_user() -> str:
        username = flask.request.json.get('username')
        password = flask.request.json.get('password')
        interface.user.update_user(username, password)
        return "0"
        
    @app.route('/api/becomeAdmin', methods=['POST'])
    def become_admin() -> bool:
        username = flask.request.json.get('username')
        return json.dumps(interface.user.become_admin(username))

    @app.route('/api/existUser', methods=['POST'])
    def exist_User()->str:
        username=flask.request.json.get('username')
        return json.dumps(interface.user.exist_user(username))

# ================= article route =================
    @app.route('/api/getAllArticles', methods=['POST'])
    def get_all_articles() -> str:
        course = flask.request.json.get('course')
        user = flask.request.json.get('user')
        articles = interface.article.get_review_articles(course)
        article_list = []
        for article in articles:
            if article['path'].startswith('http'):
                continue
            avg_score = interface.score.get_avg_score(article['id'])
            my_score = interface.score.get_user_article_score(article['id'], user)
            article['avg_score'] = avg_score
            article['my_score'] = my_score
            article_list.append(article)
        return json.dumps(article_list)

    @app.route('/api/getAllUrl', methods=['POST'])
    def get_all_url() -> str:
        course = flask.request.json.get('course')
        user = flask.request.json.get('user')
        articles = interface.article.get_review_articles(course)
        article_list = []
        for article in articles:
            if article['path'].startswith('http'):
                avg_score = interface.score.get_avg_score(article['id'])
                my_score = interface.score.get_user_article_score(article['id'], user)
                article['avg_score'] = avg_score
                article['my_score'] = my_score
                article_list.append(article)
        return json.dumps(article_list)

    @app.route('/api/getUserRecentArticles', methods=['POST'])
    def get_user_recent_articles() -> str:
        username = flask.request.json.get('username')
        return interface.article.get_recent_articles(username)

    @app.route('/api/updateArticle', methods=['POST'])
    def update_article() -> None:
        article_id = flask.request.json.get('id')
        json = interface.article.get_article(article_id)
        if json == '':
            return 'Article not found'
        course = flask.request.json.get('course')
        uploader = flask.request.json.get('uploader')
        title = flask.request.json.get('title')
        course = json['course'] if course is None else course
        uploader = json['uploader'] if uploader is None else uploader
        title = json['title'] if title is None else title
        interface.article.update_article(article_id, course, uploader, title)

    @app.route('/api/deleteArticle', methods=['POST'])
    def delete_article() -> None:
        article_id = flask.request.json.get('id')
        interface.article.delete_article(article_id)

    @app.route('/api/uploadArticle', methods=['POST'])
    def upload_article() -> bool:
        course_name = flask.request.form.get('course')
        course_name = str(course_name)
        file_dir = os.path.join(SAVING_PATH, course_name)
        if not os.path.exists(file_dir):
            os.makedirs(file_dir)
        path_type = flask.request.form.get('type')
        if path_type == 'file':
            f = flask.request.files.get('file')
            path = os.path.join(file_dir, f.filename)
            f.save(path)
        elif path_type == 'url':
            path = flask.request.form.get('url')
            if not path.startswith('http'):
                path = 'https://' + path
        # 处理 path 的反斜杠
        path = path.replace('\\', '/')
        return json.dumps(interface.article.add_article(path, course_name, flask.request.form.get('uploader'), flask.request.form.get('title')))

    @app.route('/api/downloadArticle', methods=['POST'])
    def download_article() -> None:
        article_id = flask.request.json.get('id')
        path = interface.article.get_article_path(article_id)['path']
        return flask.send_file(path, as_attachment=True)

# ================= course route =================
    @app.route('/api/addCourse', methods=['POST'])
    def add_course() -> None:
        course = flask.request.json.get('course')
        content = flask.request.json.get('content')
        file_dir = os.path.join(SAVING_PATH, course)
        if not os.path.exists(file_dir):
            os.makedirs(file_dir)
        file_dir = os.path.join(file_dir, 'content.md')
        with open(file_dir, 'w') as f:
            f.write(content)
        # 处理 path 的反斜杠
        path = path.replace('\\', '/')
        interface.course.add_course(course, file_dir)

    @app.route('/api/getCourseContent', methods=['POST'])
    def get_course_content() -> str:
        course = flask.request.json.get('course')
        file_dir = interface.course.get_course_path(course)
        with open(file_dir, 'r') as f:
            return f.read()

    @app.route('/api/deleteCourse', methods=['POST'])
    def delete_course() -> None:
        course = flask.request.json.get('course')
        interface.course.delete_course(course)

# ================= comment route =================
    @app.route('/api/addComment', methods=['POST'])
    def add_comment() -> None:
        course = flask.request.json.get('course')
        username = flask.request.json.get('username')
        content = flask.request.json.get('content')
        interface.comment.add_comment(course, username, content)
        return "Done"

    @app.route('/api/getComment', methods=['POST'])
    def get_comment() -> str:
        id = flask.request.json.get('id')
        return interface.comment.get_comment(id)

    @app.route('/api/getAllComments', methods=['POST'])
    def get_all_comments() -> str:
        course = flask.request.json.get('course')
        
        return interface.comment.get_all_comments(course)

    @app.route('/api/getUserAllComments', methods=['POST'])
    def get_user_all_comments() -> str:
        username = flask.request.json.get('username')
        return interface.comment.get_user_all_comments(username)

    @app.route('/api/getUserCommentNum', methods=['POST'])
    def get_user_comments_num() -> str:
        username = flask.request.json.get('username')
        return interface.comment.get_user_comments_num(username)

    @app.route('/api/getUserBlockInfo', methods=['POST'])
    def get_user_comment_likes_number() -> str:
        username = flask.request.json.get('username')
        return interface.comment.get_UserBlock_Information(username)

    @app.route('/api/deleteComment', methods=['POST'])
    def delete_comment() -> None:
        id = flask.request.json.get('id')
        interface.comment.delete_comment(id)
        
    @app.route('/api/updateComment', methods=['POST'])
    def update_comment() -> None:
        id = flask.request.json.get('id')
        content = flask.request.json.get('content')
        interface.comment.update_comment(id, content)

# ================= score route =================
    @app.route('/api/addScore', methods=['POST'])
    def add_score() -> None:
        username = flask.request.json.get('username')
        course = flask.request.json.get('id')
        score = int(flask.request.json.get('score'))
        interface.score.add_score(course, username, score)
        return "Done"

    @app.route('/api/getAllScores', methods=['POST'])
    def get_all_scores() -> str:
        username = flask.request.json.get('username')
        return interface.score.get_user_all_scores(username)

    @app.route('/api/updateScore', methods=['POST'])
    def update_score() -> None:
        username = flask.request.json.get('username')
        course = flask.request.json.get('id')
        score = flask.request.json.get('score')
        interface.score.update_score(course, username, score)

    @app.route('/api/deleteScore', methods=['POST'])
    def delete_score() -> None:
        username = flask.request.json.get('username')
        course = flask.request.json.get('id')
        interface.score.delete_score(course, username)

# ================= vote route =================
    @app.route('/api/vote', methods=['POST'])
    def vote() -> None:
        username = flask.request.json.get('username')
        comment_id = flask.request.json.get('id')
        vote_type = flask.request.json.get('type')
        interface.vote.vote(comment_id, username, vote_type)
        return "Done"

    @app.route('/api/getAllVotes', methods=['POST'])
    def get_all_votes() -> str:
        username = flask.request.json.get('username')
        return interface.vote.get_all_votes(username)

# ================= review route =================
    @app.route('/api/review', methods=['POST'])
    def review() -> None:
        reviewer = flask.request.json.get('reviewer')
        id = flask.request.json.get('id')
        review = flask.request.json.get('review')
        interface.article.review_article(id, reviewer, review)
        return 'Done'
    
    @app.route('/api/getUnreviewArticle', methods=['POST'])
    def get_unreview_article() -> str:
        articles = interface.article.get_unreview()
        article_list = []
        for article in articles:
            if article['path'].startswith('http'):
                continue
            article_list.append(article)
        return json.dumps(article_list)
        # return interface.article.get_unreview()

    @app.route('/api/getUnreviewUrl', methods=['POST'])
    def get_unreview_url() -> str:
        articles = interface.article.get_unreview()
        article_list = []
        for article in articles:
            if article['path'].startswith('http'):
                article_list.append(article)
        return json.dumps(article_list)

    # @app.route('/api/getAllUrl', methods=['POST'])
    # def get_all_url() -> str:
    #     course = flask.request.json.get('course')
    #     user = flask.request.json.get('user')
    #     articles = interface.article.get_review_articles(course)
    #     article_list = []
    #     for article in articles:
    #         if article['path'].startswith('http'):
    #             avg_score = interface.score.get_avg_score(article['id'])
    #             my_score = interface.score.get_user_article_score(article['id'], user)
    #             article['avg_score'] = avg_score
    #             article['my_score'] = my_score
    #             article_list.append(article)
    #     return json.dumps(article_list)